import request from '@/utils/request'

// 获取所有项目
export function getAllProjects(name, status, priority) {
  return request({
    url: '/api/kanban/projects',
    method: 'get',
    params: { name, status, priority }
  })
}

// 根据ID获取项目详情
export function getProjectById(id) {
  return request({
    url: `/api/kanban/projects/${id}`,
    method: 'get'
  })
}

// 创建项目
export function createProject(data) {
  return request({
    url: '/api/kanban/projects',
    method: 'post',
    data
  })
}

// 更新项目
export function updateProject(id, data) {
  return request({
    url: `/api/kanban/projects/${id}`,
    method: 'put',
    data
  })
}

// 删除项目
export function deleteProject(id) {
  return request({
    url: `/api/kanban/projects/${id}`,
    method: 'delete'
  })
}

// 获取项目成员列表
export function getProjectMembers(projectId) {
  return request({
    url: `/api/kanban/projects/${projectId}`,
    method: 'get'
  }).then(response => {
    console.log('项目详情API响应:', response)
    if (response.code === '200' && response.data) {
      console.log('项目成员字符串:', response.data.projectMembers)
      // 将逗号分隔的成员字符串转换为成员对象数组
      const membersStr = response.data.projectMembers
      if (membersStr && membersStr.trim()) {
        const memberNames = membersStr.split(',').map(name => name.trim()).filter(name => name)
        console.log('解析后的成员名称:', memberNames)
        const memberObjects = memberNames.map((name, index) => ({
          id: index + 1,
          name: name,
          username: name, // 添加username字段，与name保持一致
          avatar: `https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png`
        }))
        console.log('转换后的成员对象:', memberObjects)
        return {
          ...response,
          data: memberObjects
        }
      } else {
        console.warn('项目成员字符串为空或无效:', membersStr)
      }
    } else {
      console.error('API响应格式错误:', response)
    }
    return {
      ...response,
      data: []
    }
  }).catch(error => {
    console.error('获取项目成员API调用失败:', error)
    return {
      code: '500',
      msg: '网络错误',
      data: []
    }
  })
}